﻿using log4net;
using Newtonsoft.Json.Linq;
using per.esmool.utils;
using System.Collections.Generic;

namespace FlowSimulate {

    public class ResourceDispatcher {

        private static readonly ILog LOG = LogManager.GetLogger(typeof(ResourceDispatcher));

        readonly Dictionary<string, Dictionary<string, List<string>>> resources;

        public ResourceDispatcher(string resourceDefinitionFile) {
            var data = YamlKit.ParseFile<JArray>(resourceDefinitionFile);
            var m0 = new Dictionary<string, Dictionary<string, List<string>>>();
            foreach (var item in data) {
                if (item is not JObject) continue;
                var json = item as JObject;
                
                var module = json.Value<string>("Module");
                if (!m0.ContainsKey(module))
                    m0.Add(module, []);
                var m1 = m0[module];

                var stage = json.Value<string>("Stage");
                if (!m1.ContainsKey(stage))
                    m1.Add(stage, []);
                var list = m1[stage];

                var resources = json.Value<JArray>("Resources");
                foreach (var element in resources) {
                    if (element.Type != JTokenType.String) continue;
                    var file = element.Value<string>();
                    list.Add(file);
                }
            }
            this.resources = m0;
        }

        public List<string> this[string module, string stage] {
            get {
                if (!this.resources.ContainsKey(module))
                    return null;
                var m1 = this.resources[module];
                if (!m1.ContainsKey(stage))
                    return null;
                var list = m1[stage];
                return new List<string>(list);
            }
        }
    }
}